﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace RMS.Common
{

    /// <summary>
    /// 文件或文件夹操作帮助类
    /// </summary>
    public class FileHelper
    {

        /// <summary>
        /// 检查文件是否存在，不存在则创建目录和空文件
        /// </summary>
        /// <param name="path">文件全路径</param>
        public static void CheckFilePath(string path)
        {
            if (!File.Exists(path))
            {
                string map = Path.GetFullPath(Path.GetDirectoryName(path));
                CheckFolderPath(map);
                File.Create(path).Dispose();
            }
        }
        /// <summary>
        /// 判断文件夹路径是否存在，不存在则创建文件夹
        /// </summary>
        /// <param name="path">文件夹全路径</param>
        public static void CheckFolderPath(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
        
        /// <summary>
        /// 上传文件自动加时间戳文件加，按时间戳生成文件名的文件保存，并返回保存后的相对路径
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <param name="FileUpladAudio">保存的相对路径</param>
        /// <param name="message">输出信息</param>
        /// <returns></returns>
        public static bool SaveAutoName(HttpPostedFileBase file, string FileUpladAudio, out string message)
        {
            bool result = false;
            var dt = DateTime.Now.ToString("yyyyMMdd");
            var uploadPath = System.Web.HttpContext.Current.Server.MapPath("~" + FileUpladAudio) + dt + "\\";
            if (file == null)
            {
                message = "NoFile";
                return result;
            }
            CheckFolderPath(uploadPath);
            string fileName = file.FileName;
            string ext = file.FileName.Substring(file.FileName.LastIndexOf('.'));
            fileName = DateTime.Now.Ticks + ext;
            file.SaveAs(uploadPath + fileName);
            string returnData = dt + "/" + fileName;
            result = true;
            message = FileUpladAudio + returnData;
            return result;
        }
    }
}
